import { queryTagSections } from '@/services/api';
import { useQuery } from '@tanstack/react-query';
import type { IPagination, IQueryParams, ISection, ITag } from '@/interfaces';
import { useState } from 'react';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import { useSearchParams } from 'next/navigation';
import useToast from '@/hooks/useToast';

export default function QueryTagSections({ details }: { details: ITag }) {
  const { show } = useToast();
  const urlSearchParams = useSearchParams();
  const [params, setParams] = useState<IQueryParams>({
    page: urlSearchParams?.has('page')
      ? parseInt(urlSearchParams.get('page') + '')
      : 0,
  });

  const queryTagSectionsQuery = useQuery(
    ['/forum', '/tags', details.id, '/sections', params],
    async (context) => {
      return (await queryTagSections({
        id: context.queryKey[2] + '',
        query: context.queryKey[4] as any,
      })) as IPagination<ISection>;
    },
    {
      keepPreviousData: true,
    },
  );

  function onClickPrevious() {
    const data = queryTagSectionsQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: '数据不存在',
      });
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = queryTagSectionsQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: '数据不存在',
      });
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  if (queryTagSectionsQuery.data) {
    const data = queryTagSectionsQuery.data;

    return (
      <div className="card">
        <div className="card-header bg-transparent text-muted">
          <i className="bi bi-list me-2"></i>
          版块
        </div>
        <div className="card-body">
          <div className="table-responsive">
            <table className="table table-hover align-middle">
              <thead>
                <tr className="text-nowrap">
                  <th scope="col" className="w-10 fw-normal">
                    ID
                  </th>
                  <th scope="col" className="w-10 fw-normal">
                    名称
                  </th>
                </tr>
              </thead>
              <tbody>
                {data.content.map((item) => {
                  return (
                    <tr key={item.id} className="text-nowrap">
                      <td>{item.id}</td>
                      <td>{item.name}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>

            {data.content.length === 0 && (
              <div className="text-center text-muted">暂无版块</div>
            )}

            <div className="my-4">
              <nav aria-label="版块分页">
                <ul className="pagination justify-content-end">
                  <li className="page-item">
                    <a
                      onClick={onClickPrevious}
                      className="page-link cursor-pointer"
                    >
                      上一页
                    </a>
                  </li>
                  <li className="page-item">
                    <a
                      onClick={onClickNext}
                      className="page-link cursor-pointer"
                    >
                      下一页
                    </a>
                  </li>
                </ul>
              </nav>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (queryTagSectionsQuery.error) {
    return <Alert message={queryTagSectionsQuery.error} type="error" />;
  }

  return <AlertLoad />;
}
